<template>
    <!-- 查询区域 -->
    <div class="inventory-manage-page" style="width: 100%;">
      <el-card class="filter-card">
        <el-form :inline="true" :model="searchForm" class="filter-form">
          <el-form-item label="盘点单号">
            <el-input v-model="searchForm.taskCode" placeholder="请输入盘点单号" clearable />
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select v-model="searchForm.status" placeholder="请选择" clearable style="width: 120px;">
              <el-option label="等待审核" :value="1" />
              <el-option label="审核成功" :value="2" />
              <el-option label="审核失败" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getAllInventoryManagement()">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <el-card class="table-card" style="margin-top: 18px;">
        <div class="table-toolbar">
          <el-button type="primary" size="small" @click="adddialogVisible = true">新增</el-button>
          <el-button size="small" @click="handleReset">刷新</el-button>
        </div>
        <el-table 
          v-loading="loading"
          :data="tableData" 
          border 
          style="width: 100%; margin-top: 12px;">
          <el-table-column type="selection" width="50" />
          <el-table-column prop="taskCode" label="盘点单号" width="150" />
          <el-table-column prop="taskType" label="盘点类型" width="150" />
          <el-table-column prop="status" label="状态" width="200">
            <template #default="scope">
              <el-tag type="warning" v-if="scope.row.status==1">等待审核</el-tag>
              <el-tag type="success" v-if="scope.row.status==2">审核成功</el-tag>
              <el-tag type="danger" v-if="scope.row.status==3">审核失败</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="approver" label="审核人" width="250" />
          <el-table-column prop="approvalOpinion" label="审核意见" width="250" />
          <el-table-column prop="creator" label="制单人" width="250" />
          <el-table-column prop="creationTime" label="创建时间" width="250">
            <template #default="scope">
              {{ scope.row.creationTime ? scope.row.creationTime.substring(0,10).replace('T',' ') : '' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="scope">
              <el-link type="primary" @click="">查看</el-link>
              <el-link type="primary" @click="" style="margin: 0 8px;">编辑</el-link>
              <el-link type="danger" @click="handleDelete(scope.row)" style="margin: 0 8px;">删除</el-link>
              <el-link type="warning" @click="">审核</el-link>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="pageInfo.pageIndex"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
          style="margin-top: 20px;"
        />
      </el-card>
    </div>

    <!-- 新增盘点单弹窗 -->
    <el-dialog v-model="adddialogVisible" title="新增盘点单" width="1000px" :close-on-click-modal="false" @closed="resetForm">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="盘点单号" prop="taskCode">
              <el-input v-model="ruleForm.taskCode" placeholder="可不填写，自动生成" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单时间" prop="creationTime">
              <el-date-picker v-model="ruleForm.creationTime" type="date" placeholder="请选择" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单人" prop="creator">
              <el-input v-model="ruleForm.creator" placeholder="请输入制单人" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="descs">
              <el-input v-model="ruleForm.descs" type="textarea" :rows="3" placeholder="请输入备注信息" maxlength="300" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 产品信息 -->
      <el-card>
        <div style="margin-bottom: 10px;">
          <span style="font-weight: bold;">产品信息</span>
          <el-button type="primary" size="small" style="float: right;" @click="productDialogVisible = true">+ 选择产品</el-button>
        </div>
        <el-table :data="productList" border>
          <el-table-column type="selection" width="50" />
          <el-table-column prop="productName" label="产品名称" />
          <el-table-column prop="productCode" label="产品编码" />
          <el-table-column prop="spec" label="规格" />
          <el-table-column prop="batchNo" label="批次">
            <template #default="scope">
              <el-input v-model="scope.row.batchNo" placeholder="输入" />
            </template>
          </el-table-column>
          <el-table-column prop="warehouse" label="仓库" />
          <el-table-column prop="location" label="库位" />
          <el-table-column prop="stock" label="库存" />
          <el-table-column prop="count" label="盘点数">
            <template #default="scope">
              <el-input v-model="scope.row.count" placeholder="输入" />
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-link @click="saveProductRow(scope.row)">保存</el-link>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <template #footer>
        <el-button @click="adddialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)" :loading="loading">提交</el-button>
      </template>
    </el-dialog>

    <!-- 选择产品弹窗 -->
    <el-dialog v-model="productDialogVisible" title="选择产品" width="800px">
      <el-table :data="allProducts" @selection-change="handleProductSelect">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="productCode" label="产品编码" />
        <el-table-column prop="spec" label="规格" />
        <!-- 可根据实际添加更多字段 -->
      </el-table>
      <template #footer>
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addSelectedProducts">保存</el-button>
      </template>
    </el-dialog>
</template>
  
<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import http from '@/api/http'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize } from 'element-plus'

const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  "id": 0,
  "taskCode": '',
  "taskType": '',
  "status": 1,
  "approver": '',
  "approvalOpinion": '',
  "creator": "",
  "creationTime": '',
  "descs": ''
})

const rules = reactive<FormRules>({
  taskCode: [
    { required: true, message: '盘点单号不能为空', trigger: 'blur' },
  ],
  creator: [
    { required: true, message: '制单人不能为空', trigger: 'blur' },
  ],
  descs: [
    { required: true, message: '备注不能为空', trigger: 'blur' },
  ],
})

const adddialogVisible = ref(false)
const loading = ref(false)

// 分页信息
const pageInfo = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 重置表单
const resetForm = () => {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields()
  }
  Object.assign(ruleForm, {
    id: 0,
    taskCode: '',
    taskType: '',
    status: '待审核',
    approver: '',
    approvalOpinion: '',
    creator: '',
    creationTime: '',
    descs: ''
  })
}

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        loading.value = true
        const res = await http.post('/api/InventoryManagement/AddInventoryManagement', ruleForm)
        if (res > 0) {
          ElMessage.success('新增成功')
          adddialogVisible.value = false
          resetForm()
          getAllInventoryManagement()
        }
      } catch (error) {
        ElMessage.error('新增失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}


// 查询条件
const searchForm = reactive({
  taskCode: '',
  status: '',
})
const tableData = ref([])
// 查询方法
const getAllInventoryManagement = async () => {
  await http.get(`/api/InventoryManagement/GetAllInventoryManagement?taskCode=${searchForm.taskCode}&status=${searchForm.status}&PageIndex=${pageInfo.pageIndex}&PageSize=${pageInfo.pageSize}`)
  .then(res => {
    tableData.value=res;    
    pageInfo.total=res.total
    })
}

// 重置搜索条件
const handleReset = () => {
  searchForm.taskCode = ''
  searchForm.status = ''
  pageInfo.pageIndex = 1
  getAllInventoryManagement()
}


// 处理分页变化
const handlePageChange = (page: number) => {
  pageInfo.pageIndex = page
  getAllInventoryManagement()
}

const handleSizeChange = (size: number) => {
  pageInfo.pageSize = size
  pageInfo.pageIndex = 1
  getAllInventoryManagement()
}

// 删除盘点任务
//供应商的删除
const handleDelete=(row:any)=> {
  ElMessageBox.confirm(
    '确定要删除该供应商吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      http.get('api/InventoryManagement/DeleteInventoryManagement?id='+row.id)
      .then(res => {
        if (res> 0) {
          ElMessage.success('删除成功')
          getAllInventoryManagement();
        } else {
          ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '您取消了操作',
      })
    })
}

const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const productDialogVisible = ref(false)
const productList = ref<any[]>([]) // 已选产品
const allProducts = ref<any[]>([]) // 所有可选产品
const selectedProducts = ref<any[]>([])

// 模拟获取所有产品（实际应从接口获取）
const fetchAllProducts = async () => {
  allProducts.value = [
    { productName: '设备箱', productCode: '000187', spec: '10040100' },
    { productName: 'J29B泡沫活性炭滤', productCode: '000180', spec: '个' },
    // ...更多产品
  ]
}

// 选择产品时触发
const handleProductSelect = (rows: any[]) => {
  selectedProducts.value = rows
}

// 点击"保存"按钮，将选中的产品添加到表格
const addSelectedProducts = () => {
  // 去重
  const codes = productList.value.map(p => p.productCode)
  selectedProducts.value.forEach(p => {
    if (!codes.includes(p.productCode)) {
      productList.value.push({ ...p, batchNo: '', warehouse: '', location: '', stock: '', count: '' })
    }
  })
  productDialogVisible.value = false
}

// 保存单行产品（可根据实际需求处理）
const saveProductRow = (row: any) => {
  ElMessage.success('保存成功')
}

// 打开弹窗时加载产品
watch(productDialogVisible, (val) => {
  if (val) fetchAllProducts()
})

onMounted(() => {
  getAllInventoryManagement()
})
</script>
  
<style scoped>
.footer-btns {
  margin: 32px auto 0 auto;
  max-width: 1200px;
  display: flex;
  justify-content: center;
  gap: 32px;
}
</style>
  

  

